<template>
  <div class="imgUploadDemo">
    <el-form
      :model="form"
      ref="ruleForm"
      label-width="180px"
      class="form"
      size="small"
    >
      <el-form-item label="商品列表封面图：" prop="default_image">
        <div class="imgUpload">
          <el-upload
            ref="defaultImgUpload"
            action
            :auto-upload="false"
            :show-file-list="false"
            list-type="picture-card"
            :on-change="handleDefaultSuccess"
          >
            <img
              v-if="form.default_image"
              :src="form.default_image"
              class="defaultImg"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="imgSize">
            （建议尺寸为220像素*220像素长宽比例1:1的图片）
          </div>
        </div>
      </el-form-item>

      <el-form-item label="商户详情页头部轮播图：" prop="swiperList">
        <div class="imgUpload">
          <div class="merchantDetailImg imgDiv">
            <viewer :images="form.swiperList">
              <dragImgItem
                class="imgItem"
                v-for="(item, index) of form.swiperList"
                :key="index"
                :index="index"
                :imgSrc="item"
                @setCurDragImg="setCurDragImg(index, 1)"
                @clearCurDragImg="clearCurDragImg(1)"
                @dragImg="dragSwiperImg(index, 1)"
                @removeImg="removeSwiper(item)"
              >
              </dragImgItem>
            </viewer>
          </div>
          <div class="merchantDetailUpload">
            <el-upload
              action
              ref="upload"
              :auto-upload="false"
              :show-file-list="false"
              list-type="picture-card"
              :on-change="handleSwiperSuccess"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </div>
        <div style="clear: both"></div>
        <div class="imgSize">
          （建议尺寸为600像素*600像素长宽比例1:1的图片），支持长按鼠标左键拖拽图片交换位置
        </div>
      </el-form-item>
    </el-form>
    <!-- 图片裁剪弹窗-start -->
    <ImgCropper
      ref="myCropper"
      :imgCropperOptions="imgCropperOptions"
      @getFile="getFile"
      @upAgain="upAgain"
    ></ImgCropper>
    <!-- 图片裁剪弹窗-end -->
  </div>
</template>
<script>
import dragImgItem from "@/components/dragImgItem"; //图片拖拽交换位置组件
import ImgCropper from "@/components/cropper"; //图片裁剪弹窗

//图片预览组件放在main.js中引入了，也可以在页面中按需引入；
// import Vue from "vue";
// import Viewer from "v-viewer";
// import "viewerjs/dist/viewer.css";
// Vue.use(Viewer);

export default {
  name: "imgUploadDemo",
  components: {
    dragImgItem,
    ImgCropper,
  },
  data() {
    return {
      imgCropperOptions: {
        autoCropWidth: 600, // 默认生成截图框宽度
        autoCropHeight: 600, // 默认生成截图框高度
        maximgSize: 600, // 限制图片最大宽度和高度
      },
      // 图片列表
      form: {
        default_image: "",
        swiperList: [
          "https://circle.sutpay.cn/youhuiquanyi/6083782831/goods_image463321.png",
          "https://circle.sutpay.cn/youhuiquanyi/6083782831/goods_image296439.png",
          "https://circle.sutpay.cn/youhuiquanyi/6083782831/goods_image144881.png",
          "https://circle.sutpay.cn/youhuiquanyi/6083782831/goods_image098233.png",
        ],
      },
      curSwiperImgIndex: null, // 当前被拖动图片(商户详情页头部轮播图)的index
      imgUploadType: 1,
    };
  },
  methods: {
    setCurDragImg(index, type) {
      console.log("正在被拖动的图片-index", index);
      this.curSwiperImgIndex = index;
    },
    clearCurDragImg(type) {
      console.log("clearCurDragImg-type", type);
      this.curSwiperImgIndex = null;
    },

    //当前拖拽的图片进入到要交互的图片位置时触发事件
    dragSwiperImg(index) {
      // 判断被拖拽的图片与撞击的图片是否相同（通过图片的下标判断）
      if (index === this.curSwiperImgIndex) return;

      let newList = [...this.form.swiperList];
      let curImg = this.form.swiperList[this.curSwiperImgIndex]; // 当前拖动的图片
      let hitImg = this.form.swiperList[index]; // 被撞击的图片

      console.log("商户详情页头部轮播图-curImg", curImg);
      console.log("商户详情页头部轮播图-hitImg", hitImg);
      // 两张图片交换位置
      if (curImg) {
        newList.splice(this.curSwiperImgIndex, 1, hitImg);
        newList.splice(index, 1, curImg);
        // 修改当前拖动图片的index，此时已经变成被撞击图片的位置了
        this.curSwiperImgIndex = index;
        this.form.swiperList = newList;
        console.log("this.form.swiperList", this.form.swiperList);
      } else {
        this.$message.error("仅支持同类型的的图片拖拽交换位置！");
      }
    },

    //设置图片裁剪弹窗参数
    setImgCropperOptions(size) {
      console.log("设置图片裁剪弹窗参数size", size);
      this.imgCropperOptions.autoCropWidth = size;
      this.imgCropperOptions.autoCropHeight = size;
    },

    //上传商户详情头部轮播图
    async handleSwiperSuccess(res, file) {
      this.imgUploadType = 2;
      await this.setImgCropperOptions(600);
      this.$nextTick(() => {
        this.$refs.myCropper.open(res.raw || res);
      });
    },

    //上传封面图
    async handleDefaultSuccess(res, file) {
      this.imgUploadType = 1;
      await this.setImgCropperOptions(220);
      this.$nextTick(() => {
        this.$refs.myCropper.open(res.raw || res);
      });
    },

    //删除商户详情页头部轮播图
    removeSwiper(itemImg) {
      console.log("删除商品详情页头部轮播图-itemImg", itemImg);
      this.form.swiperList = this.form.swiperList.filter(
        (item, index) => {
          return item != itemImg;
        }
      );
      console.log("this.form.swiperList", this.form.swiperList);
    },

    // 点击弹框重新时触发
    upAgain() {
      if (this.imgUploadType == 1) {
        this.$refs["defaultImgUpload"].$refs[
          "upload-inner"
        ].handleClick();
      } else if (this.imgUploadType == 2) {
        this.$refs["upload"].$refs["upload-inner"].handleClick();
      }
    },

    //裁剪弹窗-确定上传回调事件
    getFile(file) {
      //如果是想拿到本地的图片信息则可通过file拿到
      console.log("file", file);
      console.log("url", URL.createObjectURL(file));
      if (this.imgUploadType == 1) {
        this.form.default_image = URL.createObjectURL(file);
      } else if (this.imgUploadType == 2) {
        this.form.swiperList.push(URL.createObjectURL(file)); //本地的图片回显
      }
      //关闭裁剪弹窗
      this.$refs.myCropper.close();

      //如果是需要拿到图片上传到服务器上后的地址，就需要通过ajax请求
      //this.uploadImage(file,this.imgUploadType);
    },

    //图片上传请求
    uploadImage(res, imgUploadType) {
      const isImgType =
        res.type === "image/bmp" ||
        "image/png" ||
        "image/jpeg" ||
        "image/jpg";
      if (!isImgType) {
        return this.$message.error(
          "上传图片只能是bmp/image/jpeg/png/jpg格式!"
        );
      }
      let formdata = new FormData();
      formdata.append("img", res);
      this.$refs.myCropper.loading = true;
      this.$axios
        .post(`/xx/upload_image/`, formdata)
        .then((res) => {
          if (imgUploadType == 1) {
            this.form.default_image = res.img_id;
          } else if (imgUploadType == 2) {
            this.form.swiperList.push(res.img_id);
          }
          //关闭裁剪弹窗
          this.$refs.myCropper.close();
        })
        .catch((err) => {
          if (err.response) {
            this.$message.error(
              err.response.data.error || err.response.data.detail
            );
          }
        })
        .finally(() => {
          this.$refs.myCropper.loading = false;
        });
    },
  },
};
</script>
<style scoped lang="scss">
.imgUploadDemo {
  padding: 100px;
  .merchantDetailImg {
    margin: 10px 0;
    .imgItem {
      position: relative;
      height: 150px;
      width: 150px;
      display: inline-block;
      border-radius: 5px;
      float: left;
      margin: 0 15px 15px 0;
      .bgImg {
        height: 150px;
        width: 150px;
        object-fit: cover;
        border: 1px solid #dcdfe6;
        border-radius: 5px;
      }
      .imgClose {
        position: absolute;
        top: 0;
        right: 0;
        width: 30px;
        margin-top: -13px;
        margin-right: -13px;
        cursor: pointer;
      }
    }
  }
  .imgSize {
    font-size: 12px;
    line-height: 12px;
    margin-top: 0;
    float: left;
  }
  .defaultImg {
    height: 150px;
    width: 150px;
    object-fit: cover;
    border-radius: 5px;
  }
}
.imgUploadDemo ::v-deep .el-upload--picture-card {
  margin-bottom: 15px;
  border: 1px solid #c0ccda;
  border-radius: 5px;
  overflow: hidden;
}
</style>
